/* 
    by qingzhong.zeng
    简易事件代理单元
 */
type EVENT_ITEM = {
    isOnce:boolean,
    cb:Function
}

export default class EventAgent {
    private __eventAgentMap:Map<String,Array<EVENT_ITEM>>

    constructor() {
        this.__eventAgentMap = new Map()
    }

    $emit(event:String, arg?:any) {
        let cbList = this.__eventAgentMap.get(event)
        if (!cbList || cbList.length == 0) return
        cbList.forEach((item:EVENT_ITEM) => {
            item.cb(arg)
        })
        this.__eventAgentMap.set(event,cbList.filter(item => {
            return !item.isOnce
        }))
    }
    $on(event:String, cb:Function) {
        if(!this.__eventAgentMap.get(event)){
            this.__eventAgentMap.set(event,[])
        }
        let eventItem:EVENT_ITEM = {
            isOnce: false,
            cb
        }
        this.__eventAgentMap.get(event)?.push(eventItem)
    }
    $once(event:String, cb:Function) {
        this.$on(event, cb)
        let cbList = this.__eventAgentMap.get(event)
        if (!cbList || cbList.length == 0) return
        cbList[cbList.length - 1].isOnce = true
    }
    $off(event:String, cb:Function) {
        let cbList = this.__eventAgentMap.get(event)
        if (!cbList || cbList.length == 0) return
        this.__eventAgentMap.set(event,cbList.filter(item=>{
            return item.cb != cb
        }))
    }
}